package com.denghq.projectbuilder.component.amqp.Configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(RabbitProperties.class)
@Slf4j
public class RabbitConfiguration {

    @Bean
    public CachingConnectionFactory connectionFactory(RabbitProperties rabbitProperties, RabbitConfigurationProperties properties) {
        buildRabbitProperties(rabbitProperties, properties);//通过系统管理微服务获取配置构建rabbitProperties
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitProperties.getHost(),
                rabbitProperties.getPort());
        connectionFactory.setUsername(rabbitProperties.getUsername());
        connectionFactory.setPassword(rabbitProperties.getPassword());
        return connectionFactory;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(CachingConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    private void buildRabbitProperties(RabbitProperties rabbitProperties, RabbitConfigurationProperties properties) {
        while (StringUtils.isBlank(properties.getHost())) {
            log.warn("未配置rabitmq主机地址，{}", properties);
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        rabbitProperties.setHost(properties.getHost());
        rabbitProperties.setPort(properties.getPort());
        rabbitProperties.setUsername(properties.getUserName());
        rabbitProperties.setPassword(properties.getPassword());
    }


}
